package com.demo.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.entity.DischargeSummary;
import com.demo.entity.Patient;
import com.demo.entity.Vo.*;
import com.demo.entity.VtePreventive;
import com.demo.entity.from.DvtScreeningExcle;
import com.demo.entity.from.PatientExcle;
import com.demo.entity.from.VtePreventionExcle;
import com.demo.enums.*;
import com.demo.mapper.DischargeSummaryMapper;
import com.demo.mapper.DvtDiagnoseMapper;
import com.demo.mapper.PatientMapper;
import com.demo.mapper.VtePreventiveMapper;
import com.demo.response.Result;
import com.demo.service.ExportDataService;
import com.demo.service.IPatientService;
import com.demo.service.IUserService;
import com.demo.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 数据导出实现类
 */
@Service
@Slf4j
public class ExportDataServiceImp implements ExportDataService {
    @Resource
    PatientMapper patientMapper;
    @Resource
    VtePreventiveMapper vtePreventiveMapper;
    @Resource
    DvtDiagnoseMapper dvtDiagnoseMapper;
    @Resource
    DischargeSummaryMapper dischargeSummaryMapper;
    @Autowired
    IPatientService iPatientService;
    @Autowired
    IUserService iUserService;

    /**
     * 数据导出
     *
     * @param response
     * @param type               导出信息类型  1.患者信息  2.VTE防治评估 3.DVT筛查诊断 4.出院总结信息
     * @param patientExcle       患者信息【条件对象】
     * @param vtePreventionExcle VTE防治评估【条件对象】
     * @param dvtScreeningExcle  DVT筛查诊断【条件对象】
     * @return
     */
    @Override
    public Result patientExport(HttpServletResponse response, ExportInfoTypeEnum type, PatientExcle patientExcle, VtePreventionExcle vtePreventionExcle, DvtScreeningExcle dvtScreeningExcle) {
        log.info("对象信息：" + patientExcle);
        switch (type) {
            case PATIENT_INFO:
                return Result.success(getPatientList(patientExcle));
            case VTE_INFO:
                return Result.success(getVtePreventiveList(vtePreventionExcle));
            case DVT_INFO:
                return Result.success(getDvtDiagonseList(dvtScreeningExcle));
            case OUT_HOSPITAL_INFO:
                return Result.success(getSummaryList());
        }
        return Result.error("其他错误");
    }


    /**
     * 通过传入条件，返回患者信息列表
     *
     * @param
     * @return
     */
    @Override
    public List<PatientExportVo> getPatientList(PatientExcle patientExcle) {
        if (patientExcle == null) {
            patientExcle = new PatientExcle();
        }
        List<PatientExportVo> exportVos = new ArrayList<>();
        patientExcle.setHospitalType(PatientHospitalTypeEnum.IN_HOSPITAL.getValue());
        //未出院
        if (!patientExcle.getHospitalType().equals(PatientHospitalTypeEnum.OUT_HOSPITAL.getValue()) || patientExcle.getHospitalType() == null) {
            QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(!StrUtil.hasEmpty(patientExcle.getPatientName()), "patient_name", patientExcle.getPatientName());
            queryWrapper.eq(patientExcle.getGender() != null, "patient_sex", patientExcle.getGender());
            queryWrapper.between(patientExcle.getMinAge() != null && patientExcle.getMaxAge() != null, "patient_age", patientExcle.getMinAge(), patientExcle.getMaxAge());
            queryWrapper.eq(!StrUtil.hasEmpty(patientExcle.getHospitalNo()), "admission_id", patientExcle.getHospitalNo());
            if (patientExcle.getHospitalType() != null) {
                queryWrapper.isNull("discharge_time");
            }
            if (!StrUtil.hasEmpty(patientExcle.getHospitalizedStartTime()) && !StrUtil.hasEmpty(patientExcle.getHospitalizedEndTime())) {
                Date date = DateUtil.parse(patientExcle.getHospitalizedStartTime() + " 00:00:00");
                Date date2 = DateUtil.parse(patientExcle.getHospitalizedEndTime() + " 23:59:59");
                queryWrapper.between("admission_time", date, date2);
            }
            if (!StrUtil.hasEmpty(patientExcle.getLeaveHospitalStartTime()) && !StrUtil.hasEmpty(patientExcle.getLeaveHospitalEndTime())) {
                Date date = DateUtil.parse(patientExcle.getLeaveHospitalStartTime() + " 00:00:00");
                Date date2 = DateUtil.parse(patientExcle.getLeaveHospitalEndTime() + " 23:59:59");
                queryWrapper.between("discharge_time", date, date2);
            }
            queryWrapper.isNull("deleted_time");
            List<Patient> list = patientMapper.selectList(queryWrapper);
            for (Patient patient : list) {
                PatientExportVo exportVo = new PatientExportVo();
                BeanUtils.copyProperties(patient, exportVo);
                if (patient.getPatientSex().equals(1)) {
                    exportVo.setGender("男");
                } else {
                    exportVo.setGender("女");
                }
                exportVo.setPatientBirthdate(DateUtil.formatDate(patient.getPatientBirthdate()));
                exportVos.add(exportVo);
            }
            log.info("在院返回的数据信息：" + exportVos.size());
        }

        //只有选择出院，才能选择【出院转归，是否非预期死亡，是否肺血栓栓塞症】条件，原因：此3个条件值存在于出院总结中
        if (patientExcle.getHospitalType().equals(2)) {
            QueryWrapper<DischargeSummary> query = new QueryWrapper<>();
            query.eq(patientExcle.getExpectDie() != null, "is_expected_death", patientExcle.getExpectDie());
            query.eq(patientExcle.getPulmonary() != null, "is_pte", patientExcle.getPulmonary());
            query.eq(patientExcle.getLapseTo() != null, "discharge_whereabouts", patientExcle.getLapseTo());
            query.select("patient_id");
            List<DischargeSummary> summaryList = dischargeSummaryMapper.selectList(query);

            List<Integer> ids = new ArrayList<>();
            for (DischargeSummary summary : summaryList) {
                ids.add(summary.getPatientId());
            }

            QueryWrapper<Patient> wrapper = new QueryWrapper<>();
            wrapper.eq(StrUtil.hasEmpty(patientExcle.getPatientName()), "patient_name", patientExcle.getPatientName());
            wrapper.eq(patientExcle.getGender() != null, "patient_sex", patientExcle.getGender());
            wrapper.between(patientExcle.getMinAge() != null && patientExcle.getMaxAge() != null, "patient_age", patientExcle.getMinAge(), patientExcle.getMaxAge());
            wrapper.eq(StrUtil.hasEmpty(patientExcle.getHospitalNo()), "admission_id", patientExcle.getHospitalNo());
            if (patientExcle.getHospitalType() != null) {
                wrapper.isNotNull("discharge_time");
            }
            if (StrUtil.hasEmpty(patientExcle.getHospitalizedStartTime()) && StrUtil.hasEmpty(patientExcle.getHospitalizedEndTime())) {
                Date date = DateUtil.parse(patientExcle.getHospitalizedStartTime() + " 00:00:00");
                Date date2 = DateUtil.parse(patientExcle.getHospitalizedEndTime() + " 23:59:59");
                wrapper.between("admission_time", date, date2);
            }
            if (StrUtil.hasEmpty(patientExcle.getLeaveHospitalStartTime()) && StrUtil.hasEmpty(patientExcle.getLeaveHospitalEndTime())) {
                Date date = DateUtil.parse(patientExcle.getLeaveHospitalStartTime() + " 00:00:00");
                Date date2 = DateUtil.parse(patientExcle.getLeaveHospitalEndTime() + " 23:59:59");
                wrapper.between("discharge_time", date, date2);
            }
            wrapper.isNull("deleted_time");
            wrapper.in("patient_id", ids);
            List<Patient> list = patientMapper.selectList(wrapper);

            for (Patient patient : list) {
                PatientExportVo exportVo = new PatientExportVo();
                BeanUtils.copyProperties(patient, exportVo);
                if (patient.getPatientSex().equals(1)) {
                    exportVo.setGender("男");
                } else {
                    exportVo.setGender("女");
                }
                exportVo.setPatientBirthdate(DateUtil.formatDate(patient.getPatientBirthdate()));
                exportVos.add(exportVo);
            }
            log.info("出院返回的数据信息：" + exportVos.size());
        }
        return exportVos;
    }

    /**
     * 通过传入条件，返回患者VTE评估诊断列表
     *
     * @param vtePreventionExcle
     * @return
     */
    @Override
    public List<VtePreventiveExportVo> getVtePreventiveList(VtePreventionExcle vtePreventionExcle) {
        if (vtePreventionExcle == null) {
            vtePreventionExcle = new VtePreventionExcle();
        }
        List<VtePreventiveExportVo> list = new ArrayList<>();

        //todo 防治措施字段找不到,暂时
        QueryWrapper<VtePreventive> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(vtePreventionExcle.getAssessType() != null, "preventive_type", vtePreventionExcle.getAssessType());
        queryWrapper.eq(vtePreventionExcle.getRiskLevel() != null, "preventive_risk_rank", vtePreventionExcle.getRiskLevel());
        if (vtePreventionExcle.getMinGrade() != null && vtePreventionExcle.getMaxGrade() != null) {
            queryWrapper.between("preventive_risk_score", vtePreventionExcle.getMinGrade(), vtePreventionExcle.getMaxGrade());
        }
        queryWrapper.isNull("deleted_user_id");
        List<VtePreventive> vtePreventives = vtePreventiveMapper.selectList(queryWrapper);

        for (VtePreventive preventive : vtePreventives) {
            VtePreventiveExportVo exportVo = new VtePreventiveExportVo();
            BeanUtils.copyProperties(preventive, exportVo);
            exportVo.setPatientName(iPatientService.vtePatievtName(preventive.getPatientId()));
            if (preventive.getPreventiveType() == PreventiveTypeEnum.CAPRINI.getValue()) {
                exportVo.setPreventiveTypeName(PreventiveTypeEnum.CAPRINI.getDesc());
            }
            if (preventive.getPreventiveType() == PreventiveTypeEnum.PADUA.getValue()) {
                exportVo.setPreventiveTypeName(PreventiveTypeEnum.PADUA.getDesc());
            }
            if (preventive.getPreventiveRiskRank() != null) {
                if (preventive.getPreventiveType() == PreventiveTypeEnum.CAPRINI.getValue()) {
                    if (preventive.getPreventiveRiskRank() == PreventiveRiskRankEnum.CAPRINI_JI_DI.getValue()) {
                        exportVo.setPreventiveTypeName(PreventiveRiskRankEnum.CAPRINI_JI_DI.getDesc());
                    }
                    if (preventive.getPreventiveRiskRank() == PreventiveRiskRankEnum.CAPRINI_DI_WEI.getValue()) {
                        exportVo.setPreventiveTypeName(PreventiveRiskRankEnum.CAPRINI_DI_WEI.getDesc());
                    }
                    if (preventive.getPreventiveRiskRank() == PreventiveRiskRankEnum.CAPRINI_ZHONG_WEI.getValue()) {
                        exportVo.setPreventiveTypeName(PreventiveRiskRankEnum.CAPRINI_ZHONG_WEI.getDesc());
                    }
                    if (preventive.getPreventiveRiskRank() == PreventiveRiskRankEnum.CAPRINI_GAO_WEI.getValue()) {
                        exportVo.setPreventiveTypeName(PreventiveRiskRankEnum.CAPRINI_GAO_WEI.getDesc());
                    }
                } else if (preventive.getPreventiveType() == PreventiveTypeEnum.PADUA.getValue()) {
                    if (preventive.getPreventiveRiskRank() == PreventiveRiskRankEnum.PADUA_DI_WEI.getValue()) {
                        exportVo.setPreventiveTypeName(PreventiveRiskRankEnum.PADUA_DI_WEI.getDesc());
                    } else if (preventive.getPreventiveRiskRank() == PreventiveRiskRankEnum.PADUA_GAO_WEI.getValue()) {
                        exportVo.setPreventiveTypeName(PreventiveRiskRankEnum.PADUA_GAO_WEI.getDesc());
                    }
                }

            }
            exportVo.setCreatedUserName(iUserService.getUnameById(preventive.getCreatedUserId()));
            if (preventive.getSignUserId() != null) {
                exportVo.setSignUserName(iUserService.getUnameById(preventive.getSignUserId()));
            }
            list.add(exportVo);
        }
        return list;
    }

    /**
     * 根据传入条件，返回患者DVT诊断列表信息
     *
     * @param dvtScreeningExcle
     * @return
     */
    @Override
    public List<DvtDiagonseExportVo> getDvtDiagonseList(DvtScreeningExcle dvtScreeningExcle) {
        if (dvtScreeningExcle == null) {
            dvtScreeningExcle = new DvtScreeningExcle();
        }
        List<DvtDiagonseExportVo> list = new ArrayList<>();

        List<DvtDiagonseVo> dvtList = dvtDiagnoseMapper.getDvtList(dvtScreeningExcle.getClinicPossibility(), dvtScreeningExcle.getDDimer(), dvtScreeningExcle.getVenousPressure(), dvtScreeningExcle.getWessMin(), dvtScreeningExcle.getWessMax());
        for (DvtDiagonseVo diagonseVo : dvtList) {
            DvtDiagonseExportVo exportVo = new DvtDiagonseExportVo();
            BeanUtils.copyProperties(diagonseVo, exportVo);
            if (diagonseVo.getDiagnoseOpportunity() != null) {
                exportVo.setDiagnoseOpportunityName(this.getStringDiagnose(diagonseVo.getDiagnoseOpportunity()));
            }
            if (diagonseVo.getDetectRank() != null) {
                exportVo.setDetectRankName(this.getdetectRankName(diagonseVo.getDetectRank()));
            }
            if (diagonseVo.getDimerResult() != null) {
                exportVo.setDimerResult(this.getDimerResult(diagonseVo.getDimerResult()));
            }
            if (diagonseVo.getVenousResult() != null) {
                exportVo.setVenousResultName(this.getVenousResult(diagonseVo.getVenousResult()));
            }
            if (diagonseVo.getDiagnoseResult() != null) {
                exportVo.setDiagnoseResultName(this.getDiagnoseResultName(diagonseVo.getDiagnoseResult()));
            }
            list.add(exportVo);
        }
        return list;
    }

    /**
     * 根据传入条件，返回出院总结信息列表 TODO 视图界面暂时无条件，所以此处为空
     *
     * @return
     */
    @Override
    public List<DischargeSummaryExportVo> getSummaryList() {
        List<DischargeSummaryExportVo> list = new ArrayList<>();
        //TODO 默认条件,查询本周的出院信息列表
        Date startTime = DateUtil.parse(TimeUtil.getWeekStart());
        Date endTime = DateUtil.parse(TimeUtil.getWeekEnd());

        List<DischargeSummaryVo> summaryVos = dischargeSummaryMapper.getSummaryExport(null, startTime, endTime);
        for (DischargeSummaryVo summaryVo : summaryVos) {
            DischargeSummaryExportVo dischargeSummaryExportVo = new DischargeSummaryExportVo();
            BeanUtils.copyProperties(summaryVo, dischargeSummaryExportVo);
            if (summaryVo.getDischargeWhereabouts() != null) {
                switch (DischargeWhereAboutEnum.getByValue(summaryVo.getDischargeWhereabouts())) {
                    case YI_ZHU_CHU_YUAN:
                        dischargeSummaryExportVo.setDischargeWhereabouts(DischargeWhereAboutEnum.YI_ZHU_CHU_YUAN.getDesc());
                        break;
                    case FEI_YI_ZHU_CHU_YUAN:
                        dischargeSummaryExportVo.setDischargeWhereabouts(DischargeWhereAboutEnum.FEI_YI_ZHU_CHU_YUAN.getDesc());
                        break;
                    case SI_WANG:
                        dischargeSummaryExportVo.setDischargeWhereabouts(DischargeWhereAboutEnum.SI_WANG.getDesc());
                        break;
                    case OTHER:
                        dischargeSummaryExportVo.setDischargeWhereabouts(DischargeWhereAboutEnum.OTHER.getDesc());
                        break;
                }
            }

            if (summaryVo.getIsExpectedDeath() != null) {
                if (summaryVo.getIsExpectedDeath().equals(1)) {
                    dischargeSummaryExportVo.setIsExpectedDeath("是");
                }
                if (summaryVo.getIsExpectedDeath().equals(2)) {
                    dischargeSummaryExportVo.setIsExpectedDeath("否");
                }
            }

            if (summaryVo.getIsPte() != null) {
                if (summaryVo.getIsPte().equals(1)) {
                    dischargeSummaryExportVo.setIsPte("是");
                }
                if (summaryVo.getIsPte().equals(2)) {
                    dischargeSummaryExportVo.setIsPte("否");
                }
            }

            if (summaryVo.getIsIpc() != null) {
                if (summaryVo.getIsIpc().equals(1)) {
                    dischargeSummaryExportVo.setIsIpc("是");
                }
                if (summaryVo.getIsIpc().equals(2)) {
                    dischargeSummaryExportVo.setIsIpc("否");
                }
            }

            if (summaryVo.getIsGcs() != null) {
                if (summaryVo.getIsGcs().equals(1)) {
                    dischargeSummaryExportVo.setIsGcs("是");
                }
                if (summaryVo.getIsGcs().equals(2)) {
                    dischargeSummaryExportVo.setIsGcs("否");
                }
            }
            list.add(dischargeSummaryExportVo);
        }
        return list;
    }

    /**
     * 通过诊断ID，返回时机名称
     *
     * @param number
     * @return
     */
    @Override
    public String getStringDiagnose(Integer number) {
        String str = "";
        switch (number) {
            case 1:
                str = "新入";
                break;
            case 2:
                str = "术后";
                break;
            case 3:
                str = "分娩";
                break;
            case 4:
                str = "出院";
                break;
            case 5:
                str = "病情变化";
                break;
            case 6:
                str = "定期";
                break;
            default:
                str = "未知";
                break;
        }
        return str;
    }

    /**
     * 通过临床可能性，返回可能性名称
     *
     * @param number
     * @return
     */
    @Override
    public String getdetectRankName(Integer number) {
        String str = "";
        switch (number) {
            case 1:
                str = "低度";
                break;
            case 2:
                str = "中度";
                break;
            case 3:
                str = "高度";
                break;
            default:
                str = "未知";
                break;
        }
        return str;
    }

    /**
     * 通过D二聚体，返回结果字符
     *
     * @param number
     * @return
     */
    @Override
    public String getDimerResult(Integer number) {
        if (number.equals(0)) {
            return "阴性";
        } else if (number.equals(1)) {
            return "阳性";
        }
        return "未知";
    }

    /**
     * 通过静脉加压缠身检查，返回结果集字符
     *
     * @param number
     * @return
     */
    @Override
    public String getVenousResult(Integer number) {
        if (number.equals(0)) {
            return "阴性";
        } else if (number.equals(1)) {
            return "阳性";
        }
        return "未知";
    }

    /**
     * 通过诊断结果ID，返回结果字符
     *
     * @param number
     * @return
     */
    @Override
    public String getDiagnoseResultName(Integer number) {
        if (number.equals(0)) {
            return "诊断中";
        }
        if (number.equals(1)) {
            return "排除";
        }
        if (number.equals(2)) {
            return "确诊";
        }
        return "未知";
    }
}
